import json
from datetime import datetime

import requests


class Ali():
    def __init__(self, conf: dict) -> None:
        self.api_key = conf.get("api_key")
        self.model = conf.get("model", "qwen-max")  # 默认使用 qwen-max 模型
        self.api = conf.get("api")
        self.converstion_list = {}
        # 获取当前时间
        now = datetime.now()
        # 格式化时间为 "YYYYMMDD" 格式
        self.date = now.strftime("%Y%m%d")

    @staticmethod
    def value_check(conf: dict) -> bool:
        if conf and conf.get("api_key"):
            return True
        return False

    def __repr__(self):
        return 'Ali'

    def completions(self, model, content, wxid):
        """
        调用阿里云 API 获取回复
        """
        end_response = "暂时不可用哦，请稍后再试"
        if self.api:
            url = f"{self.api}/api/api/v1/ai/wechat-user-ask"
            headers = {
                'Content-Type': 'application/json'
            }
            data = {
                "sessionId": wxid + "_" + self.date,
                "userId": wxid,
                "robotId": "121212",
                "companyId": 126,
                "role": "user",
                "content": content
            }
            response = requests.post(url, headers=headers, verify=False, json=data)
            if response.status_code == 200:
                response_json = json.loads(response.content)
                if response_json.get("code") == 2000:
                    pass
                    end_response = response_json.get("data")
                else:
                    end_response = response_json.get("message")
        res = {}
        choices = [
            {
                'message': {
                    'content': end_response
                }
            }
        ]
        res['choices'] = choices
        return res

    def get_answer(self, msg: str, wxid: str, **args) -> str:
        self._update_message(wxid, str(msg), "user")
        response = self.completions(
            model=self.model,
            content=msg,
            wxid=wxid
        )
        resp_msg = response['choices'][0].get('message')
        answer = resp_msg.get('content')
        self._update_message(wxid, answer, "assistant")
        return answer

    def _update_message(self, wxid: str, msg: str, role: str) -> None:
        if wxid not in self.converstion_list.keys():
            self.converstion_list[wxid] = []
        content = {"role": role, "content": str(msg)}
        self.converstion_list[wxid].append(content)


if __name__ == "__main__":
    from configuration import Config
    config = Config().ALI
    if not config:
        exit(0)

    ali = Ali(config)
    rsp = ali.get_answer("你好")
    print(rsp)
